package com.changgou.web.order.controller;

import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

/**
 * 订单页面渲染controller
 */
@Controller
@RequestMapping("/worder")
public class WebOrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;

    /**
     * 进入到结算页面
     * @return
     */
    @GetMapping("/ready")
    public String ready(Model model) {
        //1. 获取收货人地址列表
        List<Address> addressList = addressFeign.findAddressListByUsername();

        //2. 获取默认收货地址
        Address defaultAddress = null;
        if (addressList != null) {
            for (Address address : addressList) {
                if ("1".equals(address.getIsDefault())) {
                    defaultAddress = address;
                }
            }
        }
        //3. 获取购物车数据
        Map<String, Object> cartMap = cartFeign.list();

        //4. 封装返回给页面的数据
        //默认收货地址
        model.addAttribute("defaultAddress", defaultAddress);
        //收货地址列表
        model.addAttribute("addressList", addressList);
        //购物车
        model.addAttribute("cartMap", cartMap);
        return "order";
    }


    /**
     * 消费者在页面点击提交订单按钮进入这个方法
     * @param order 订单对象
     * @return
     */
    @PostMapping("/submit")
    public String submit(Order order) {
        //1. 通过feign远程调用技术, 调用保存订单接口
        orderFeign.add(order);
        //2. 重定向到预支付接口
        return "redirect:http://web.changgou.com:8001/api/wpay/nativePay";
    }
}
